package com.xxl.sso.core.util;

import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.StringTokenizer;

@Slf4j
public abstract class StringUtils {

	/**
	 *
	 * @param str
	 * @return
	 */
	public static boolean hasLength(String str) {
		return (str != null && !str.isEmpty());
	}

	/**
	 *
	 * @param str
	 * @return
	 */
	public static boolean hasText(String str) {
		return (hasLength(str) && containsText(str));
	}

	private static boolean containsText(CharSequence str) {
		int strLen = str.length();
		for (int i = 0; i < strLen; i++) {
			if (!Character.isWhitespace(str.charAt(i))) {
				return true;
			}
		}
		return false;
	}

	/**
	 *
	 * @param str
	 * @param delimiters
	 * @param trimTokens
	 * @param ignoreEmptyTokens
	 * @return
	 */
	public static String[] tokenizeToStringArray(
			String str, String delimiters, boolean trimTokens, boolean ignoreEmptyTokens) {

		if (str == null) {
			return null;
		}

		StringTokenizer st = new StringTokenizer(str, delimiters);
		List<String> tokens = new ArrayList<String>();
		while (st.hasMoreTokens()) {
			String token = st.nextToken();
			if (trimTokens) {
				token = token.trim();
			}
			if (!ignoreEmptyTokens || token.length() > 0) {
				tokens.add(token);
			}
		}
		return toStringArray(tokens);
	}

	/**
	 *
	 * @param collection
	 * @return
	 */
	public static String[] toStringArray(Collection<String> collection) {
		if (collection == null) {
			return null;
		}
		return collection.toArray(new String[collection.size()]);
	}

	public static String getSubFromSencond2LastSymbol(String origin,String symbol){
		return origin.substring(origin.lastIndexOf(symbol,origin.lastIndexOf(symbol)-1));
	}

	public static String getSecondLevelDomain(String domain){
		if(null != domain && !"".equals(domain)){
			try{
				domain = getSubFromSencond2LastSymbol(domain,".");
				if(null != domain && "/".equals(String.valueOf(domain.charAt(domain.length() - 1)))){
					domain = domain.substring(1, domain.length()-1);//去掉开头的'.'
				}
			}catch(Exception e){
				log.error("StringUtils getSecondLevelDomain error:{}",e);
			}
		}
		return domain;
	}

}
